<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Jwt\SelfJwt;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

/**
 * @Controller(prefix="/ecommerce/php/test")
 * Class IndexController
 * @package App\Controller
 */
class TestController extends BaseAbstractController
{

    /**
     * @GetMapping(path="jwt")
     * @return string|array
     */
    public function jwt()
    {
        $reqData = $this->request->query();

        $validator = $this->validationFactory->make($reqData,[
            'userId' => 'required|integer',
            'isAdmin' =>  'required|integer',
        ]);

        if($validator->fails()) {
            return self::returnFailed($validator->errors()->first());
        }

        $validData = $validator->validated();

        $data = ["user" => json_encode(['UserId' => $validData['userId'], 'IsAdmin' => $validData['isAdmin']])];
        return SelfJwt::encode($data);
    }

    /**
     * @GetMapping(path="decode")
     * @return array
     */
    public function decode(): array
    {
        $jwt = $this->request->query('jwt');
        $data = SelfJwt::decode($jwt);

        return ['data' => $data];
    }

}
